package org.jaaksi.kottlindemo.test

import android.animation.ValueAnimator
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.doOnEnd
import androidx.core.view.animation.PathInterpolatorCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jaaksi.kottlindemo.databinding.FragmentTestanimBinding
import org.jaaksi.kottlindemo.ui.SecondActivity
import org.jetbrains.anko.startActivity
import java.util.*

class TestAnimFragment : Fragment() {
    private lateinit var binding: FragmentTestanimBinding
    private var heartBeatAnim: ValueAnimator? = null

    private val dotHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            binding.tvDot.text = when (msg.what) {
                1 -> "."
                2 -> ".."
                else -> "..."
            }
            sendEmptyMessageDelayed((msg.what + 1) % 3, 1000)

            // 播放音效
            lifecycleScope.launch {
                println(">> lifecycleScope launch")
                delay(500)
                startHeartBeatAnim()
                activity

            }
        }

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
//        println("savedInstanceState = $savedInstanceState $this")
        binding = FragmentTestanimBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        binding.btnStart.setOnClickListener {
            dotHandler.sendEmptyMessage(3)
        }

        GlobalScope.launch {
            // 这里的时间短，并不会造成内存泄漏
            delay(5000)
            // Fragment销毁后，getActivity = null,isAdded = false
//            println(">> activity = $activity")
//            println(">> isAdd = $isAdded")
//            println(binding.btnStart.toString())
        }

        binding.btnNext.setOnClickListener {
            requireActivity().startActivity<SecondActivity>()
            lifecycleScope.launch {
//                println(">> 跳转后 lifecycleScope.launch")
                delay(2000)
                // todo 被销毁后，协程会自动关闭。所以这里不用判断
//                println(">> 跳转后 delay 2000")
            }
        }
    }

    private fun startHeartBeatAnim() {
        if (heartBeatAnim == null) {
            heartBeatAnim = ValueAnimator.ofFloat(1f, 1.2f, 1f).apply {
                interpolator = PathInterpolatorCompat.create(0.25f, 0.1f, 0.25f, 1f)
                duration = 600
                addUpdateListener {
//                    if (!isAdded) return@addUpdateListener
                    println(">> it.animatedValue = ${it.animatedValue}")
                    binding.ivHeartBeat.scaleX = it.animatedValue as Float
                    binding.ivHeartBeat.scaleY = it.animatedValue as Float
                }
            }
        }
        if (heartBeatAnim?.isStarted == false) {
            heartBeatAnim?.start()
        }
    }

    private fun cancelHeartBeatAnim() {
        heartBeatAnim?.end()
        heartBeatAnim?.cancel()
    }

    override fun onDestroyView() {
        println(">> onDestroyView")
//        cancelHeartBeatAnim()
        dotHandler.postDelayed({
            dotHandler.removeCallbacksAndMessages(null)
        }, 3000)
        super.onDestroyView()
    }
}